<template>
  <Tree show-line checkable default-expand-all :data="permissions" :check-strictly="true" :field-names="{ key: 'id', title: 'name' }" :expanded-keys="checkedKeys" v-model:checked-keys="checkedKeys">
    <template #extra="node">
      <span class="ml16">{{ node.data.key }}</span>
    </template>
  </Tree>
  <Button @click="Modal.close">取消</Button>
  <Button type="primary" @click="onSave">保存</Button>
</template>

<script setup lang="ts">
import { Message, Button, Tree, Modal } from '@idmy/ui'
import { onMounted, ref } from 'vue'
import { createOrUpdateRolePermissionRefs, getTreeByAppId, listPermissionIdsByRoleId } from './services'

const { parentData, dialogOk } = defineProps({ parentData: Object, dialogOk: Function })
const roleId = parentData.id
const appId = parentData.appId

const permissions = ref([])
const checkedKeys = ref([])

const load = async () => {
  const tree = await getTreeByAppId(appId)
  permissions.value = [tree]
  checkedKeys.value = await listPermissionIdsByRoleId(roleId)
}
onMounted(load)

const onSave = async () => {
  await createOrUpdateRolePermissionRefs(roleId, checkedKeys.value)
  Message.success('保存成功')
  dialogOk()
}
</script>
